package in.muton.edushare.pages.folder;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.components.messaging.api.FileUploadMessage;
import in.muton.edushare.pages.EduShareBasePage;
import in.muton.edushare.pages.common.EdusharePanel;
import in.muton.edushare.panels.folder.ChangeFolderVisibilityPanel;
import in.muton.edushare.panels.folder.CreateNewFolderPanel;
import in.muton.edushare.panels.folder.FileListPanel;
import in.muton.edushare.panels.upload.MultipleFileUploadButtonPanel;
import in.muton.edushare.wicket.models.CayenneList;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.wicket.MarkupContainer;
import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.CSSPackageResource;
import org.apache.wicket.markup.html.JavascriptPackageResource;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

import com.edushare.common.dao.FileDirectoriesDAO;
import com.edushare.common.dao.FilesUploadedDAO;
import com.edushare.common.vo.FileDirTypes;
import com.edushare.common.vo.FileDirectories;
import com.edushare.common.vo.FilesUploaded;
import com.edushare.common.vo.Messages;
import com.edushare.common.vo.Users;

public class FolderBasePanel extends EdusharePanel {
	
	private static final long serialVersionUID = 3158585079995478080L;
	private IModel<FileDirectories> dirModel;
	private EduShareBasePage parentPage;
	
	public FolderBasePanel(String id, IModel<FileDirectories> directoryModel, EduShareBasePage page){
		super(id, directoryModel,page);
		this.dirModel = directoryModel;
		this.parentPage = page;
		add(CSSPackageResource.getHeaderContribution(FolderBasePanel.class, "FolderBasePanel.css"));
		add(JavascriptPackageResource.getHeaderContribution(FolderBasePanel.class, "FolderBasePanel.js"));
		
		if(isAuthorized())
		{
			loadPanel();
		}
		else
		{
			loadWarning();
		}
		
		
	}

	private void loadPanel() {
		add(new Label("curFolderVisi",new PropertyModel<String>(this, "folderVisibilityStr")));
		add(new BreadcrumbFrag("dirBreadcrumbs", this, dirModel));
		if(FolderHelper.isEditable(dirModel.getObject(), getLoggedInUser()) && dirModel.getObject().getDirType().getCreatorType()!= FileDirTypes.CREATOR_TYPE_SYSTEM){
			add(new ChangeFolderVisibilityPanel("visChangePanel", dirModel, parentPage));
		}
		else{
			add(new EmptyPanel("visChangePanel"));
		}
		final WebMarkupContainer dirStats = new WebMarkupContainer("dirStats");
		dirStats.setOutputMarkupId(true);
		dirStats.add(new Label("totalStat", new PropertyModel<Integer>(this,"totalStat")));
		dirStats.add(new Label("subDirsStat", new PropertyModel<Integer>(this,"subDirsStat")));
		dirStats.add(new Label("filesStat", new PropertyModel<Integer>(this,"filesStat")));
		add(dirStats);
		
		final Form<Void> ffUploadForm = new Form<Void>("ffuploadForm");
		add(ffUploadForm);
		
		final FileListPanel fileListing = new FileListPanel("dirListing", dirModel, parentPage);
		fileListing.setOutputMarkupId(true);
		add(fileListing);
		
		if(
				dirModel.getObject().getReadPerm().equals(FileDirectories.PERM_PUBLIC)&&
				!FolderHelper.isEditable(dirModel.getObject(), getLoggedInUser()))
		{
			ffUploadForm.setVisible(false);
		}
		
		MultipleFileUploadButtonPanel uploadButton = new MultipleFileUploadButtonPanel("ffupload", dirModel) {
			
			@Override
			public void onUploadWindowClose(AjaxRequestTarget target) {
				//Reload File and Stats list to reflect the update!
				target.addComponent(fileListing);
				target.addComponent(dirStats);
				//send message
				List<FilesUploaded> ful = EduShareSession.get().getFileUploadedInLastUpload();
				for(FilesUploaded fu : ful){
					new FileUploadMessage(fu, FileUploadMessage.EVENT_FILE_UPLOADED)
					.setReciever(new FileDirectoriesDAO(getORMInterface()).getOwnerObject(dirModel.getObject()))
					.setReciever(new CayenneList<Users>(new FileDirectoriesDAO(getORMInterface()).getAccessingUserList(dirModel.getObject())))
					.setPrivacy(Messages.PRIVACY_TYPE_NONE)
					.send();
				}
			}
		};
		ffUploadForm.add(uploadButton);
		if(	dirModel.getObject().getDirType().getDirType().equals(FileDirTypes.DEFAULT_GALLERY) || 
			dirModel.getObject().getDirType().getDirType().equals(FileDirTypes.DEFAULT_DIR)
		){
			add(new EmptyPanel("newDirForm"));
		}else{
			add(new CreateNewFolderPanel("newDirForm", dirModel, parentPage));
		}
		
		
	}

	private void loadWarning() {
		// TODO Auto-generated method stub
		
	}

	private boolean isAuthorized() {
		// TODO Auto-generated method stub
		return true;
	}
	
	public String getFolderVisibilityStr(){
		return FolderHelper.getFolderReadPermissionString(this.dirModel.getObject().getReadPerm(),this.dirModel.getObject().getOwnerType());
	}
	
	public int getTotalStat(){
		return getSubDirsStat()+getFilesStat();
	}
	
	public int getSubDirsStat(){
		List<String> userVisibility = FolderHelper.getUserVisibilityUnderDir(getLoggedInUser(), this.dirModel.getObject());
		List<FileDirectories> subDirs= new FileDirectoriesDAO(getORMInterface()).getChildren(dirModel.getObject(), userVisibility);
		return subDirs!=null?subDirs.size():0;
	}
	
	public int getFilesStat(){
		List<FilesUploaded> filesList = new FilesUploadedDAO(getORMInterface()).getFiles(dirModel.getObject());
		return filesList!=null?filesList.size():0;
	}
	
	public class BreadcrumbFrag extends Fragment{

		public BreadcrumbFrag(String id, MarkupContainer container, IModel<FileDirectories> model) {
			super(id, "breadcrumbFrag", container, model);
			FileDirectories fd = (FileDirectories)getDefaultModelObject();
			int level = fd.getLevel();
			ArrayList<FileDirectories> fdl = new ArrayList<FileDirectories>();
			fdl.add(fd);
			while(level>0){
				fd = fd.getParent();
				level = fd.getLevel();
				fdl.add(fd);
			}
			Collections.reverse(fdl);
			ListView<IModel<FileDirectories>> lv = new ListView<IModel<FileDirectories>>("bcItem", new CayenneList<FileDirectories>(fdl)){

				private static final long serialVersionUID = 3665093701659973084L;

				@Override
				protected void populateItem(ListItem<IModel<FileDirectories>> item) {
					FileDirectories fd = item.getModelObject().getObject();
					PageParameters parameters = FolderHelper.getDirectoryPageParameters(fd);
					BookmarkablePageLink<Void> bpl = new BookmarkablePageLink<Void>("bcLink", parentPage.getClass(), parameters);
					bpl.add(new Label("bcTitle", fd.getDirectoryName()));
					Label titlePlain = new Label("titlePlain", fd.getDirectoryName());
					titlePlain.setVisible(false);
					if(item.getIndex()==getList().size()-1){
						bpl.setVisible(false);
						titlePlain.setVisible(true);
					}
					item.add(bpl);
					item.add(titlePlain);
				}
				
			};
			add(lv);
		}
		
	}
	
}
